package com.ny.service.impl;

import com.ny.entity.User;
import com.ny.mapper.UserMapper;
import com.ny.service.UserService;
import com.ny.utils.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> findAllUser() {
        return userMapper.findAllUser();
    }

    @Override
    public User login(String username, String password) {
        // 登录时验证密码
        User user = userMapper.findUserByUsername(username);
        if (user != null && PasswordUtil.verifyPassword(password, user.getPassword())) {
            return user;
        }
        return null;
    }

    @Override
    public Object registerUser(User user) {
        // 注册时加密密码
        String encryptedPassword = PasswordUtil.encryptPassword(user.getPassword());
        user.setPassword(encryptedPassword);
        return userMapper.insertUser(user);
    }

    @Override
    public User findUserByUsername(String username) {
        return userMapper.findUserByUsername(username);
    }
    
    @Override
    public User findUserByEmail(String email) {
        return userMapper.findUserByEmail(email);
    }
    
    @Override
    public int updatePassword(int userId, String newPassword) {
        // 更新密码时加密
        String encryptedPassword = PasswordUtil.encryptPassword(newPassword);
        return userMapper.updatePassword(userId, encryptedPassword);
    }
    
    @Override
    public int updateEmail(int userId, String email) {
        return userMapper.updateEmail(userId, email);
    }
}
